import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qunaimedical/components/custom_text_field.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/configs.dart';
import 'package:qunaimedical/values/urls.dart';

class RegisterPage extends StatefulWidget {
  static const String routeName = '/register';

  const RegisterPage({Key? key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();

  // final TextEditingController _codeController = TextEditingController();
  final TextEditingController _pwd1Controller = TextEditingController();
  final TextEditingController _pwd2Controller = TextEditingController();
  bool _showPwd1 = false;
  bool _showPwd2 = false;

  // bool _codeSend = false;

  @override
  void initState() {
    super.initState();
    if (kDebugMode) {
      _usernameController.text = "aaaa";
      _phoneController.text = "18710711835";
      _pwd1Controller.text = "000000";
      _pwd2Controller.text = "000000";
    }
  }

  @override
  void dispose() {
    super.dispose();
    _usernameController.dispose();
    _phoneController.dispose();
    // _codeController.dispose();
    _pwd1Controller.dispose();
    _pwd2Controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("注册")),
      body: CommonUtil.generateWidgetOfWideScreen(_buildBody()),
    );
  }

  Widget _buildBody() {
    List<Widget> children = [
      Container(
        padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(16))),
        child: Column(
          children: [
            CustomTextField(
              controller: _usernameController,
              textInputAction: TextInputAction.next,
              label: "用户名(数字或字母)",
              hintText: "请输入用户名",
              onChanged: (value) {
                setState(() {});
              },
              suffixIcon: _usernameController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(CupertinoIcons.xmark_circle,
                          color: Colors.grey),
                      onPressed: () {
                        setState(() {
                          _usernameController.clear();
                        });
                      })
                  : null,
            ),
            CustomTextField(
              controller: _phoneController,
              textInputAction: TextInputAction.next,
              hintText: "请输入手机号",
              label: "手机号",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(11),
              ],
              onChanged: (value) {
                setState(() {});
              },
              suffixIcon: _phoneController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(CupertinoIcons.xmark_circle,
                          color: Colors.grey),
                      onPressed: () {
                        setState(() {
                          _phoneController.clear();
                        });
                      })
                  : null,
            ),
            // UserTypeSelector(
            //   type: "doctor",
            //   callback: (value) {},
            // ),
            CustomTextField(
              controller: _pwd1Controller,
              hintText: "请输入密码",
              label: "密码",
              textInputAction: TextInputAction.next,
              obscureText: !_showPwd1,
              suffixIcon: IconButton(
                  icon: _showPwd1
                      ? const Icon(CupertinoIcons.eye, color: Colors.grey)
                      : Image.asset(
                          'assets/images/ic_eye_close.png',
                          width: 20,
                          height: 20,
                          color: Colors.grey,
                        ),
                  onPressed: () {
                    setState(() {
                      _showPwd1 = !_showPwd1;
                    });
                  }),
            ),
            CustomTextField(
              controller: _pwd2Controller,
              hintText: "请再次输入密码",
              label: "确认密码",
              textInputAction: TextInputAction.next,
              obscureText: !_showPwd2,
              suffixIcon: IconButton(
                  icon: _showPwd2
                      ? const Icon(CupertinoIcons.eye, color: Colors.grey)
                      : Image.asset(
                          'assets/images/ic_eye_close.png',
                          width: 20,
                          height: 20,
                          color: Colors.grey,
                        ),
                  onPressed: () {
                    setState(() {
                      _showPwd2 = !_showPwd2;
                    });
                  }),
            ),
            // CustomTextField(
            //   controller: _codeController,
            //   keyboardType: TextInputType.number,
            //   inputFormatters: [
            //     FilteringTextInputFormatter.digitsOnly,
            //     LengthLimitingTextInputFormatter(6),
            //   ],
            //   hintText: "请输入验证码",
            //   label: "验证码",
            //   suffixIcon: TextButton(
            //     onPressed: _codeSend ? null : _register,
            //     child: Text(_codeSend ? "验证码已发送" : "发送验证码"),
            //   ),
            // ),
          ],
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(left: 20.0),
        child: Text(
          "请设置至少6位数的密码",
          style: Theme.of(context).textTheme.caption,
        ),
      ),
      PrimaryButton("注册", onPressed: _signUp),
    ];
    return ListView.separated(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
      itemBuilder: (BuildContext context, int index) {
        return children[index];
      },
      separatorBuilder: (BuildContext context, int index) {
        return const SizedBox(
          height: 16,
        );
      },
      itemCount: children.length,
    );
  }

  bool _checkParams() {
    String username = _usernameController.text.trim();
    String phone = _phoneController.text.trim();
    String pwd1 = _pwd1Controller.text.trim();
    String pwd2 = _pwd2Controller.text.trim();
    if (username.isEmpty) {
      ToastUtil.show("用户名不能为空。");
    } else if (phone.length != 11) {
      ToastUtil.show("请输入有效的手机号码。");
    } else if (pwd1.length < 6 || pwd2.length < 6) {
      ToastUtil.show("密码格式有误，请重新输入。");
    } else if (pwd1 != pwd2) {
      ToastUtil.show("两次输入的密码不一致，请重新输入。");
    } else {
      return true;
    }
    return false;
  }

  void _signUp() async {
    CommonUtil.hideKeyboard(context);
    if (_checkParams()) {
      String username = _usernameController.text.trim();
      String phone = _phoneController.text.trim();
      String pwd1 = _pwd1Controller.text.trim();
      DialogUtil.showWaitDialog(context);
      try {
        Response response = await XHttp.instance.post(
          Urls.REGISTER,
          queryParameters: {
            "loginName": username,
            "phone": phone,
            "password": pwd1,
            // TODO 2022-10-14 fix this to support more user type.
            "userType": UserType.doctor.name,
          },
        );
        if (mounted) {
          Navigator.pop(context);
          if (response.statusCode == 200 && response.data != null) {
            if (response.data["code"] == 0) {
              ToastUtil.show(response.data["msg"]);
            } else {
              // 群爱账号注册成功，回退到登录界面。
              Navigator.popUntil(
                  context, ModalRoute.withName(LoginPage.routeName));
            }
          }
        }
      } on DioError catch (e) {
        if (mounted) {
          Navigator.pop(context);
          CommonUtil.catchDioError(e);
        }
      }
    }
  }
}
